<template>
  <el-dialog model-value="dialogVisible" :title="dialogTitle" width="30%" @close="handleClose">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="账号" prop="username">
        <el-input v-model="form.username" />
        <el-alert v-if="form.id == -1" title="默认初始密码：123456" :closable="false" style="line-height: 10px" type="success"> </el-alert>
      </el-form-item>

      <el-form-item label="教师/学生" prop="type">
        <el-radio-group v-model="form.type">
          <el-radio :label="0">教师</el-radio>
          <el-radio :label="1">学生</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="头像" prop="avatar">
        <el-upload class="avatar-uploader" :action="getServerUrl() + 'sys/user/uploadImage'" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>

      <el-form-item label="姓名" prop="nickname">
        <el-input v-model="form.nickname" />
      </el-form-item>

      <el-form-item label="手机号" prop="phonenumber">
        <el-input v-model="form.phonenumber" />
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio :label="'0'">正常</el-radio>
          <el-radio :label="'1'">禁用</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" :rows="4" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleConfirm">确认</el-button>
        <el-button @click="handleClose">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineEmits, defineProps, ref, watch } from "vue";
import requestUtil, { getServerUrl } from "@/utils/request";
import { ElMessage } from "element-plus";

const tableData = ref([]);

const props = defineProps({
  id: {
    type: Number,
    default: -1,
    required: true,
  },
  dialogTitle: {
    type: String,
    default: "",
    required: true,
  },
  dialogVisible: {
    type: Boolean,
    default: false,
    required: true,
  },
});

const form = ref({
  id: -1,
  username: "",
  nickname: "",
  password: "123456",
  status: "0",
  phonenumber: "",
  email: "",
  remark: "",
  type: 0,
  isParty: 0, // 1==党员
  avatar: "",
});

const checkUsername = async (rule, value, callback) => {
  if (form.value.id == -1) {
    const res = await requestUtil.post("sys/user/checkUserName", { username: form.value.username });
    if (res.data.code == 500) {
      callback(new Error("账号已存在！"));
    } else {
      callback();
    }
  } else {
    callback();
  }
};

const rules = ref({
  username: [
    { required: true, message: "请输入账号" },
    { required: true, validator: checkUsername, trigger: "blur" },
  ],
  isParty: [
    { required: true, message: "请选择是否党员" },
    { required: true, trigger: "blur" },
  ],
  type: [
    { required: true, message: "请选择是教师或学生" },
    { required: true, trigger: "blur" },
  ],
  nickname: [
    { required: true, message: "请输入姓名" },
    { required: true, trigger: "blur" },
  ],
  email: [
    { required: true, message: "邮箱地址不能为空", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] },
  ],
  phonenumber: [
    { required: true, message: "手机号码不能为空", trigger: "blur" },
    { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" },
  ],
});

const formRef = ref(null);
const imageUrl = ref("");

const initFormData = async (id) => {
  const res = await requestUtil.get("sys/user/" + id);
  form.value = res.data.sysUser;
  imageUrl.value = getServerUrl() + "images/userAvatar/" + form.value.avatar;
};

const handleAvatarSuccess = (res) => {
  imageUrl.value = getServerUrl() + res.data.src;
  form.value.avatar = res.data.title;
};

const beforeAvatarUpload = (file) => {
  const isJPG = file.type === "image/jpeg";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error("图片必须是jpg格式");
  }
  if (!isLt2M) {
    ElMessage.error("图片大小不能超过2M!");
  }
  return isJPG && isLt2M;
};

watch(
  () => props.dialogVisible,
  () => {
    let id = props.id;
    if (id != -1) {
      initFormData(id);
    } else {
      imageUrl.value = "";
      form.value = {
        id: -1,
        username: "",
        password: "123456",
        status: "0",
        phonenumber: "",
        email: "",
        remark: "",
        nickname: "",
        type: 0,
        isParty: false, // 1==党员
        avatar: "",
      };
    }
  }
);

const emits = defineEmits(["update:modelValue", "initUserList"]);

const handleClose = () => {
  emits("update:modelValue", false);
};

const handleConfirm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      let result = await requestUtil.post("sys/user/save", form.value);
      let data = result.data;
      if (data.code == 200) {
        ElMessage.success("执行成功！");
        formRef.value.resetFields();
        emits("initUserList");
        handleClose();
      } else {
        ElMessage.error(data.msg);
      }
    } else {
      console.log("fail");
    }
  });
};
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
